from django import forms
from django.forms import ValidationError

from grades.models import Grade
from scores.models import Score
from students.models import Student


class ScoreForm(forms.ModelForm):
    class Meta:
        model = Score
        fields = ['title', 'student_name', 'student_number', 'grade', 'chinese_score', 'math_score', 'english_score']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['grade'].queryset = Grade.objects.all()
        self.fields['grade'].empty_label = '请选择班级'

    # clean_xxxx 对某个字段限制条件
    def clean_student_number(self):
        student_number = self.cleaned_data['student_number']
        if len(student_number) != 9:
            raise ValidationError('学号必须为9位')
        if not Student.objects.filter(student_number=student_number).exists():
            raise ValidationError(f'该【{student_number}】学号不存在')
        
        return student_number
    
    def clean_grade(self):
        grade = self.cleaned_data['grade']
        student_number = self.cleaned_data['student_number']
        if not Student.objects.filter(grade=grade, student_number=student_number).exists():
            raise ValidationError(f'该学生不是【{grade}】')
        
        return grade
    
    def clean_student_name(self):
        student_name = self.cleaned_data['student_name']
        if len(student_name) < 2 or len(student_name) > 50:
            raise ValidationError('名字长度在2-50之间')
        if not Student.objects.filter(student_name=student_name).exists():
            raise ValidationError(f'该【{student_name}】学生姓名不存在')
        return student_name